﻿using System;
using System.Linq;
using System.Linq.Expressions;
using ASPItalia.ModelVirtualCasting.Common;
using ASPItalia.ModelVirtualCasting.ObjectModel;
using System.Data;
using ASPItalia.ModelVirtualCasting.EntityFramework.Wrappers;
using System.Data.Objects;

namespace ASPItalia.ModelVirtualCasting.EntityFramework {
	public class ModelRepository : BaseRepository<Person>, IModelRepository {
        internal ModelRepository(IIncludeObjectSet<Person> objectSet)
            : base(objectSet)
        { }

		public ModelRepository(IContextContainer container) : base(container) { }

		public void InsertOnSubmit(Model entity) {
			throw new NotImplementedException();
		}

		public void Update(Model entity) {
			CurrentObjectSet.Attach(entity);
			Context.ChangeObjectState(entity, EntityState.Modified);
		}

		public void DeleteOnSubmit(Model entity) {
			CurrentObjectSet.DeleteObject(entity);
		}

		public void SubmitChanges() {
			base.SaveChanges();
		}

		public IQueryable<ModelDTO> GetRandomModels(int number) {
			var query = (from m in CurrentObjectSet.OfType<Model>()
									 select new ModelDTO {
										 Age = DateTime.Today.Year - m.BirthDate.Year,
										 Country = m.ResidenceCountry.CountryName,
										 NickName = m.NickName,
										 ImageUrl = m.Multimedia.Where(image => image is Image).FirstOrDefault().FileName
									 }).Take(number);

			return query;
		}

		public IQueryable<Model> GetAll() {
			return CurrentObjectSet.OfType<Model>();
		}

		public IQueryable<Model> Where(Expression<Func<Model, bool>> predicate) {
			return CurrentObjectSet.OfType<Model>().Where(predicate);
		}

		public long Count(Expression<Func<Model, bool>> predicate) {
			return CurrentObjectSet.OfType<Model>().Count(predicate);
		}

		public IModelRepository Include(string path) {
			CurrentObjectSet.Include(path);
			return this;
		}

		public IModelRepository EnableLazyLoading() {
			SetLazyLoading(true);
			return this;
		}

		public IModelRepository DisableLazyLoading() {
			SetLazyLoading(false);
			return this;
		}
	}
}